package me.seu.demo.test;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.test.dto.CardPageInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 有方sim卡
 *
 * @author liangfeihu
 * @since 2022/10/26 11:36
 */
@Slf4j
public class RestTemplateTest4 {

    private static String baseUrl = "http://m2m.neoway.com";
    private static final String GET_ALL_CARDS_INFO = "/api/v2/card/getAllCardInfo";

    private static final RestTemplate restTemplate = new RestTemplate();

    public static void main(String[] args) throws Exception {
        // 运营商 1：联通,2：移动，3：电信
        CardPageInfo allCardInfo = getAllCardInfo(2, 1, 100);
        log.info("[allCardInfo] json totalPage={} cardSize={} cardList={}", allCardInfo.getTotalPage(), allCardInfo.getCardInfoList().size(), JSON.toJSONString(allCardInfo.getCardInfoList()));
    }

    /**
     * 获取账户下所有卡信息
     *
     * @param operator
     * @param pageNum
     * @param pageSize
     * @return
     */
    public static CardPageInfo getAllCardInfo(Integer operator, Integer pageNum, Integer pageSize) {
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("appkey", "U2JRVVa9EiJLUomGyqcZm7KEIkWGfUOX");
        paramMap.put("nonce", random());
        paramMap.put("timestamp", genTimestamp());
        paramMap.put("pageNum", pageNum);
        paramMap.put("operator", operator);
        String sign = generateSign(paramMap, "36ba879353e3460a98a44dc9c48f3df8");
        paramMap.put("sign", sign);
        paramMap.put("pageSize", pageSize);

        String url = baseUrl + GET_ALL_CARDS_INFO;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<String> formEntity = new HttpEntity<>(JSON.toJSONString(paramMap), headers);
        ResponseEntity<JsonResult<CardPageInfo>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, formEntity, new ParameterizedTypeReference<JsonResult<CardPageInfo>>() {
        });
        if (responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
            JsonResult<CardPageInfo> jsonResult = responseEntity.getBody();
            log.info("[getAllCardInfo] paramMap={}, jsonResult={}", JSON.toJSONString(paramMap), JSON.toJSONString(jsonResult));
            return jsonResult.getData();
        } else {
            log.error("[getAllCardsInfo] statusCode={},body={}, error=", responseEntity.getStatusCodeValue(), responseEntity.getBody());
        }
        return null;
    }

    /**
     * 生成签名
     *
     * @param paramMap 参数
     * @param secret   密钥
     * @return
     */
    private static String generateSign(Map<String, Object> paramMap, String secret) {
        List<String> list = new ArrayList<>(20);
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            list.add(entry.getKey() + "=" + entry.getValue() + "&");
        }
        Collections.sort(list);
        String signParam = String.join("", list);
        String param = signParam + "secret=" + secret;
        return DigestUtils.sha1Hex(param).toUpperCase();
    }

    /**
     * 生成时间戳
     *
     * @return
     */
    private static Long genTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成5位随机数
     *
     * @return
     */
    private static Integer random() {
        return (int) ((Math.random() * 9 + 1) * 10000);
    }

}
